-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
47 lines (40 loc) · 1003 Bytes
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <vector>
using namespace std;
int findMajorityElement(vector<int>& arr) {
int count = 0, candidate = -1;
// Finding candidate
for (int num : arr) {
if (count == 0) {
candidate = num;
count = 1;
} else if (num == candidate) {
count++;
} else {
count--;
}
}
// Verifying candidate
count = 0;
for (int num : arr) {
if (num == candidate)
count++;
}
return (count > arr.size() / 2) ? candidate : -1;
}
int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
vector<int> arr(n);
cout << "Enter " << n << " elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int result = findMajorityElement(arr);
if (result != -1)
cout << "The majority element is: " << result << endl;
else
cout << "No majority element found." << endl;
return 0;
}